package com.learn.hibernatevalidator.chapter06.constraintvalidatorpayload;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorContext;

/**
 * @author: liyf
 * @create: 2025-01-14 22:51
 **/
public class ZipCodeValidator implements ConstraintValidator<ZipCode, String> {

    @Override
    public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
        if (object == null) {
            return true;
        }

        boolean isValid = false;

        String countryCode = constraintContext
                .unwrap(HibernateConstraintValidatorContext.class)
                .getConstraintValidatorPayload(String.class);

        if ("US".equals(countryCode)) {
            // 美国邮政编码验证逻辑
            return object.matches("\\d{5}");
        } else if ("FR".equals(countryCode)) {
            // 法国邮政编码验证逻辑
            return object.matches("\\d{5}");
        } else {
            // 默认验证逻辑
            return object.matches("\\d+");
        }
    }
}
